package com.michael.retail.auth.service;

import com.michael.retail.commons.pojo.global.R;
import com.michael.retail.sys.api.feign.OAuth2ClientFeign;
import com.michael.retail.sys.api.pojo.entity.OAuth2Client;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

/**
 * 类功能描述:
 * <pre>
 *   自定义 ClientDetailsService
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/7/5 19:11
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@Service("oauth2ClientDetailsService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OAuth2ClientDetailsService implements ClientDetailsService {

    private final OAuth2ClientFeign feign;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        R<OAuth2Client> result = feign.getOAuth2ClientByClientId(clientId);
        if (R.succeed().getCode().equals(result.getCode())) {
            OAuth2Client client = result.getData();
            BaseClientDetails clientDetails = new BaseClientDetails(
                    client.getClientId(),
                    client.getResourceIds(),
                    client.getScope(),
                    client.getAuthorizedGrantTypes(),
                    client.getAuthorities(),
                    client.getWebServerRedirectUri()
            );
            clientDetails.setClientSecret(client.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(client.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(client.getRefreshTokenValidity());
            return clientDetails;
        } else {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
    }
}
